package gui;

import java.util.ArrayList;

import javax.swing.BoundedRangeModel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.text.BadLocationException;

import eclMain.ChatLine;
import eclMain.Notifier;
import gui.options.TextManagerSettings;

public class ECMTextPane extends JScrollPane implements ChatListener {

	private static final long serialVersionUID = 1L;
	private JTextPane textPane = new JTextPane();
	
	private ArrayList<ChatLine> listedChat = new ArrayList<ChatLine>();
	private TextManagerSettings settings = new TextManagerSettings();
	
	public ECMTextPane() {
		this.textPane.setEditable(false);
		this.add(this.textPane);
		this.setViewportView(this.textPane); //because it doesn't automatically do this for some reason...
		this.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		this.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); //i'll just wrap the text for horizontal
		
		Notifier.addUIListener(this);
	}	
	

	@Override
	public void notifyOfChat(ChatLine newChat) {
		this.listedChat.add(newChat);
		
		//figure out if the scrollpane is at the bottom
		BoundedRangeModel brm = this.getVerticalScrollBar().getModel();
		boolean scrollBarAtBottom = (brm.getValue() >= (brm.getMaximum() - brm.getExtent() - 10)); //-10 because for some reason setting the scrollbar value to maximum... doesn't actually set it to maximum...
		
		addChatLine(newChat); //add the new chat to the textPane
		
		if (scrollBarAtBottom) //only autoscroll to the bottom, if the pane was at the bottom to begin with
			this.textPane.select(this.textPane.getDocument().getLength(), this.textPane.getDocument().getLength());
	}
	
	/**Construct the sequence of commands necessary to build the wanted string according to the settings*/
	//TODO: add the string to the textPane in piecemeal, so that I can add stylized text like highlighting keywords within the line
	private void addChatLine(ChatLine line) {
		try {
			this.textPane.getDocument().insertString(this.textPane.getDocument().getLength(), line.toString() + "\n", null);
		} catch (BadLocationException e) {
			//really, this should never happen
			Notifier.errorNotify("Failed to insert string into text area");
		}
	}
	
	public TextManagerSettings getSettings() {
		return this.settings;
	}
}
